package com.huifaapp.mall.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.google.gson.Gson;
import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.Red_PacketActivity;
import com.huifaapp.mall.activity.ShopCartActivity;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.bean.GoodsSkuCountBean;
import com.huifaapp.mall.bean.ShoppingCartBean;
import com.huifaapp.mall.bean.UserMyShoppingCart;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.Contig;
import com.huifaapp.mall.uitils.StringUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by AYD on 2016/11/21.
 * <p/>
 * 购物车Adapter
 */
public class ShoppingCartAdapter extends BaseAdapter {

    private boolean isShow = true;//是否显示编辑/完成
    private List<UserMyShoppingCart> shoppingCartBeanList;
    private CheckInterface checkInterface;
    private ModifyCountInterface modifyCountInterface;
    ModifyCountInter modifyCountInter;
    private Context context;

    public ShoppingCartAdapter(Context context) {
        this.context = context;
    }

    public void setShoppingCartBeanList(List<UserMyShoppingCart> shoppingCartBeanList) {
        this.shoppingCartBeanList = shoppingCartBeanList;
        notifyDataSetChanged();
    }

    /**
     * 单选接口
     *
     * @param checkInterface
     */
    public void setCheckInterface(CheckInterface checkInterface) {
        this.checkInterface = checkInterface;
    }

    /**
     * 改变商品数量接口
     *
     * @param modifyCountInterface
     */
    public void setModifyCountInterface(ModifyCountInterface modifyCountInterface) {
        this.modifyCountInterface = modifyCountInterface;
    }
    /**
     * 改变商品数量接口
     *
     * @param modifyCountInter
     */
    public void setModifyCountInter(ModifyCountInter modifyCountInter) {
        this.modifyCountInter = modifyCountInter;
    }
    @Override
    public int getCount() {
        return shoppingCartBeanList == null ? 0 : shoppingCartBeanList.size();
    }

    @Override
    public Object getItem(int position) {
        return shoppingCartBeanList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    /**
     * 是否显示可编辑
     *
     * @param flag
     */
    public void isShow(boolean flag) {
        isShow = flag;
        notifyDataSetChanged();
    }
    ViewHolder holder;
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_shopping_cart_layout, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final UserMyShoppingCart shoppingCartBean = shoppingCartBeanList.get(position);
        boolean choosed = shoppingCartBean.isChoosed();
        if (choosed){
            holder.ckOneChose.setChecked(true);
        }else{
            holder.ckOneChose.setChecked(false);
        }
        holder.tv_shopping_cart_ljljprice.setText("领券立减"+shoppingCartBean.getCouponAmount()+"元");
        holder.tv_shopping_cart_ljljprice_no.setText("领券立减"+shoppingCartBean.getCouponAmount()+"元");
        if(shoppingCartBean.getIsOutDate().equals("0")){//已过期，1未过期
            holder.ll_shopcart_quanhou.setVisibility(View.GONE);
            holder.tvCommodityNum.setText("¥"+shoppingCartBean.getOriginPrice());
            holder.tv_shopping_cart_ljljprice_no.setVisibility(View.GONE);
            holder.tv_shopping_cart_ljljprice.setVisibility(View.GONE);
            holder.tv_shopping_cart_ljljprice_noguoqi.setVisibility(View.VISIBLE);
        }else {
            if (shoppingCartBean.getIsRevice().equals("1")) {//已领取

                holder.tvCommodityNum.setText("¥" + shoppingCartBean.getOriginPrice());
                holder.tvCommodityNum.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                holder.tvCommodityPrice.setText("¥" + shoppingCartBean.getActualpay() + "");
                holder.tv_shopping_cart_ljljprice_no.setVisibility(View.VISIBLE);
                holder.tv_shopping_cart_ljljprice.setVisibility(View.GONE);
                holder.tv_shopping_cart_ljljprice_noguoqi.setVisibility(View.GONE);

            } else {
                holder.ll_shopcart_quanhou.setVisibility(View.GONE);
                holder.tvCommodityNum.setText("¥" + shoppingCartBean.getOriginPrice());
                holder.tv_shopping_cart_ljljprice_no.setVisibility(View.GONE);
                holder.tv_shopping_cart_ljljprice.setVisibility(View.VISIBLE);
                holder.tv_shopping_cart_ljljprice_noguoqi.setVisibility(View.GONE);
            }
        }
        holder.ll_shop_details.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, Red_PacketActivity.class);
                intent.putExtra("shopid", shoppingCartBean.getId());
                intent.putExtra("typex", "yh");
                context.startActivity(intent);
            }
        });



            if(shoppingCartBean.getParam()==""||shoppingCartBean.getParam()==null||shoppingCartBean.getParam()=="null"){
                holder.tvCommodityAttr.setText("");
            }else{
                try {
                    String parem = shoppingCartBean.getParam().substring(1, shoppingCartBean.getParam().length()).
                            substring(0, shoppingCartBean.getParam().length() - 2);
                    String attribute = parem;

                    if (!StringUtil.isEmpty(attribute)) {
                        holder.tvCommodityAttr.setText(attribute);
                    } else {
                        holder.tvCommodityAttr.setText(parem);
                    }
                }catch (Exception e){

                }

          }

        holder.tv_shopping_cart_ljljprice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                modifyCountInter.dolingquan(position);
                holder.tv_shopping_cart_ljljprice_no.setVisibility(View.VISIBLE);
                holder.tv_shopping_cart_ljljprice.setVisibility(View.GONE);

            }
        });
        holder.tvCommodityName.setText(shoppingCartBean.getGoodsName());


        holder.tvCommodityShowNum.setText(shoppingCartBean.getCount()+"");
        ImageLoader.getInstance().displayImage(shoppingCartBean.getGoodsImg(),holder.ivShowPic);

        Loadshopcartnum(shoppingCartBean.getCount(),shoppingCartBean.getCouponId());
        //单选框按钮
        holder.ckOneChose.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        shoppingCartBean.setChoosed(((CheckBox) v).isChecked());
                        checkInterface.checkGroup(position, ((CheckBox) v).isChecked());//向外暴露接口
                    }
                }
        );
        //增加按钮
        holder.ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modifyCountInterface.doIncrease(position, holder.tvCommodityShowNum, holder.ckOneChose.isChecked());//暴露增加接口
            }
        });
        //删减按钮
        holder.ivSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modifyCountInterface.doDecrease(position, holder.tvCommodityShowNum, holder.ckOneChose.isChecked());//暴露删减接口
            }
        });
//        //删除弹窗
//        holder.tvCommodityDelete.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                AlertDialog alert = new AlertDialog.Builder(context).create();
//                alert.setTitle("操作提示");
//                alert.setMessage("您确定要将这些商品从购物车中移除吗？");
//                alert.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
//                        new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                return;
//                            }
//                        });
//                alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定",
//                        new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                modifyCountInterface.childDelete(position);//删除 目前只是从item中移除
//
//                            }
//                        });
//                alert.show();
//            }
//        });
        //判断是否在编辑状态下
//        if (isShow) {
//            holder.tvCommodityName.setVisibility(View.VISIBLE);
//            holder.rlEdit.setVisibility(View.GONE);
//            holder.tvCommodityNum.setVisibility(View.VISIBLE);
//            holder.tvCommodityDelete.setVisibility(View.GONE);
//        } else {
//            holder.tvCommodityName.setVisibility(View.VISIBLE);
//            holder.rlEdit.setVisibility(View.VISIBLE);
//            holder.tvCommodityNum.setVisibility(View.GONE);
//            holder.tvCommodityDelete.setVisibility(View.VISIBLE);
//        }
        return convertView;
    }


    private void Loadshopcartnum(int count, String couponId){
//        Log.e("ShopCartActivity","url========="+ ApiManager.ADJUSTSHOPPINGCARTCOUNT+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+ AUniqueIdentifier.getDeviceId(context));
        OkHttpUtils.get().url(ApiManager.ADJUSTSHOPPINGCARTCOUNT+"?token="+SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+ AUniqueIdentifier.getDeviceId(context)+"&goodsId="+couponId+"&count="+count).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                UserMyShoppingCart list = gson.fromJson(response,UserMyShoppingCart.class);
//                if(list.getCode().equals("10000")) {
//                }else{
//                    Toast.makeText(ShopCartActivity.this,list.getMsg(),Toast.LENGTH_SHORT).show();
//                }
            }
        });
    }
    //初始化控件
    class ViewHolder {
        ImageView ivShowPic;//,tvCommodityDelete;
        TextView tvCommodityName, tvCommodityAttr, tvCommodityPrice, tvCommodityNum, tvCommodityShowNum,ivSub, ivAdd;
        CheckBox ckOneChose;
        LinearLayout rlEdit;
        TextView tv_shopping_cart_ljljprice;
        LinearLayout ll_shopcart_quanhou;
        private TextView tv_shopping_cart_ljljprice_no;
        LinearLayout ll_shop_details;
        TextView tv_shopping_cart_ljljprice_noguoqi;

        public ViewHolder(View itemView) {
            ckOneChose = (CheckBox) itemView.findViewById(R.id.ck_chose);
            ivShowPic = (ImageView) itemView.findViewById(R.id.iv_show_pic);
            ivSub = (TextView) itemView.findViewById(R.id.iv_sub);
            ivAdd = (TextView) itemView.findViewById(R.id.iv_add);
            tvCommodityName = (TextView) itemView.findViewById(R.id.tv_commodity_name);
            tvCommodityAttr = (TextView) itemView.findViewById(R.id.tv_commodity_attr);
            tvCommodityPrice = (TextView) itemView.findViewById(R.id.tv_commodity_price);
            tvCommodityNum = (TextView) itemView.findViewById(R.id.tv_commodity_num);
            tvCommodityShowNum = (TextView) itemView.findViewById(R.id.tv_commodity_show_num);
//            tvCommodityDelete = (ImageView) itemView.findViewById(R.id.tv_commodity_delete);
            rlEdit = (LinearLayout) itemView.findViewById(R.id.rl_edit);
            tv_shopping_cart_ljljprice= (TextView) itemView.findViewById(R.id.tv_shopping_cart_ljljprice);
            ll_shopcart_quanhou= (LinearLayout) itemView.findViewById(R.id.ll_shopcart_quanhou);
            tv_shopping_cart_ljljprice_no= (TextView) itemView.findViewById(R.id.tv_shopping_cart_ljljprice_no);
            ll_shop_details= (LinearLayout) itemView.findViewById(R.id.ll_shop_details);
            tv_shopping_cart_ljljprice_noguoqi= (TextView) itemView.findViewById(R.id.tv_shopping_cart_ljljprice_noguoqi);


        }
    }

    /**
     * 复选框接口
     */
    public interface CheckInterface {
        /**
         * 组选框状态改变触发的事件
         *
         * @param position  元素位置
         * @param isChecked 元素选中与否
         */
        void checkGroup(int position, boolean isChecked);
    }


    /**
     * 改变数量的接口
     */
    public interface ModifyCountInterface {
        /**
         * 增加操作
         *
         * @param position      元素位置
         * @param showCountView 用于展示变化后数量的View
         * @param isChecked     子元素选中与否
         */
        void doIncrease(int position, View showCountView, boolean isChecked);

        /**
         * 删减操作
         *
         * @param position      元素位置
         * @param showCountView 用于展示变化后数量的View
         * @param isChecked     子元素选中与否
         */
        void doDecrease(int position, View showCountView, boolean isChecked);

        /**
         * 删除子item
         *
         * @param position
         */
        void childDelete(int position);

    }
    /**
     * 改变数量的接口
     */
    public interface ModifyCountInter {
        /**
         * 领券操作
         *
         * @param position      元素位置
         *
         *
         */
        void dolingquan(int position);
    }
}
